package iap.dao;

import iap.model.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class HeadBooksDAOImpl implements HeadBooksDAO {

	Connection connection;

	public HeadBooksDAOImpl(Connection connection) {
		super();
		this.connection = connection;
	}

	@Override
	public List<Book> getAllBooksFromDB() {
		ArrayList<Book> resultList = new ArrayList<Book>();
		String queryText = "SELECT * FROM head_books;";
		ResultSet resultSet;
		Book book;
		try {
			Statement statement = connection.createStatement();
			resultSet = statement.executeQuery(queryText);
			while (resultSet.next()) {
				book = new Book();
				book.setIsbn(resultSet.getLong(1));
				book.setAuthor(resultSet.getString(2));
				book.setTitle(resultSet.getString(3));
				book.setPrice(resultSet.getInt(4));
				book.setAmountOnTheShell(resultSet.getInt(5));
				resultList.add(book);
			}
			statement.close();
			resultSet.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out
				.println("We downloaded following number of books from local copy of HQ DB : "
						+ resultList.size());
		return resultList;
	}

	@Override
	public void updateDBarchive(List<Book> actualList) {
		// TODO Auto-generated method stub
		// at first we remove all old entries...
		String queryDeleteText = "DELETE FROM head_books;";
		String queryInsertText = "INSERT INTO head_books"
				+ "(pk_isbn, authorname, title, price, specimennumber) VALUES"
				+ "(?,?,?,?,?)";
		PreparedStatement statement;
		try {
			statement = connection.prepareStatement(queryDeleteText);
			statement.executeUpdate();
			statement.close();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// ... and now we add the new ones
		PreparedStatement preparedStatement;
		if (actualList != null) {
			for (Book book : actualList) {

				try {
					preparedStatement = connection
							.prepareStatement(queryInsertText);
					preparedStatement.setLong(1, book.getIsbn());
					preparedStatement.setString(2, book.getAuthor());
					preparedStatement.setString(3, book.getTitle());
					preparedStatement.setInt(4, book.getPrice());
					preparedStatement.setInt(5, book.getAmountOnTheShell());
					preparedStatement.executeUpdate();
					preparedStatement.close();

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}

	}

}
